package com.xzx.shop_front_api.controller;

import com.xzx.shop_front_api.entity.ESNews;
import com.xzx.shop_front_api.utils.JsonResult;
import com.xzx.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.data.util.Streamable;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("api/news")
public class EsNewsController {
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;    //创建索引

    @GetMapping("create")
    public JsonResult create() {
        IndexOperations indexOperations = elasticsearchOperations.indexOps(ESNews.class);
        if (!indexOperations.exists()) {
            indexOperations.create();
        }
        return JsonResult.success("ok", null);
    }

    //索引文档
    @PostMapping("add")
    public JsonResult add(@RequestBody ESNews news) {
        news.setCreateTime(Tool.getCurrentTime());
        System.out.println(news);
        ESNews result = elasticsearchOperations.save(news);
        return JsonResult.success("添加成功", news);
    }

    //删除文档
    @GetMapping("delete")
    public JsonResult delete(@RequestParam("id") String id) {
        if (id.isEmpty()) {
            return JsonResult.failed("id不能为空");
        }
        String result = elasticsearchOperations.delete(id, ESNews.class);
        return JsonResult.success("删除成功", null);
    }

    //精确搜索
    @GetMapping("search")
    public JsonResult search(@RequestParam("wd") String wd) {
        if (wd.isEmpty()) {
        }
        System.out.println(wd);
        Criteria criteria = new Criteria("title").contains(wd);
        CriteriaQuery query = new CriteriaQuery(criteria);
        SearchHits<ESNews> hits = elasticsearchOperations.search(query, ESNews.class);
        System.out.println(hits);
        List<ESNews> newsList = hits.stream()
                .map(SearchHit::getContent)
                .toList();
        return JsonResult.success("ok", newsList);
    }

    //ik分词搜索
    @GetMapping("match")
    public JsonResult match(@RequestParam("wd") String wd) {
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                )
                .build();
        SearchHits<ESNews> searchHits = elasticsearchOperations.search(query, ESNews.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功", resultData);
    }

    // 高亮搜索
    @GetMapping("highlight")
    public JsonResult highlight(@RequestParam("wd") String wd) {
        // 创建高亮配置
        HighlightField highlightField = new HighlightField("title");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();

        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, ESNews.class);

        // 构建查询
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                )
                .withHighlightQuery(highlightQuery)
                .build();
        SearchHits<ESNews> searchHits = elasticsearchOperations.search(query, ESNews.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功", resultData);
    }

}
